package com.cy.aircompressor.main.home.systemsetting.detail;

import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;

import androidx.fragment.app.FragmentManager;
import androidx.lifecycle.Observer;

import com.cy.aircompressor.config.AirConfig;
import com.cy.aircompressor.databinding.DialogAddOrUpdateUserInfoBinding;
import com.cy.aircompressor.entity.select.SelectDict;
import com.cy.aircompressor.entity.system.UserInfo;
import com.cy.aircompressor.main.home.systemsetting.viewmodel.SystemSettingViewModel;
import com.cy.aircompressor.main.view.pop.AirDropdownPopupWindow;
import com.drug.lib.util.ToastUtil;
import com.jakewharton.rxbinding2.view.RxView;
import com.net.model.base.Resource;
import com.net.model.base.fragment.BaseVMDialogFragment;
import com.net.model.livedatas.LiveDataBus;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

public class UserInfoAddOrUpdateDialog extends BaseVMDialogFragment<DialogAddOrUpdateUserInfoBinding, SystemSettingViewModel> {
    boolean isEdit;
    UserInfo userInfo;
    AirDropdownPopupWindow mPopupWindow;
    AirDropdownPopupWindow mPopupWindowUserType;
    String powerStationId;
    String userType;

    public static void showDialogFragment(FragmentManager fragmentManager, String tag, boolean isEdit, UserInfo userInfo) {
        Bundle args = new Bundle();
        UserInfoAddOrUpdateDialog fragment = new UserInfoAddOrUpdateDialog();
        args.putSerializable("userInfo", userInfo);
        args.putBoolean("isEdit", isEdit);
        fragment.setArguments(args);
        fragment.show(fragmentManager, tag);
    }

    @Override
    protected void dataChange() {
        mViewModel.getAddUser().observe(this, new Observer<Resource<Object>>() {
            @Override
            public void onChanged(Resource<Object> objectResource) {
                objectResource.handler(new OnCallback<Object>(true, true) {
                    @Override
                    public void onSuccess(Object data) {
                        ToastUtil.show("新增成功");
                        LiveDataBus.get().with("userinfo", String.class).post("add");
                        dismiss();
                    }
                });
            }
        });
        mViewModel.getUpdateUser().observe(this, new Observer<Resource<Object>>() {
            @Override
            public void onChanged(Resource<Object> objectResource) {
                objectResource.handler(new OnCallback<Object>(true, true) {
                    @Override
                    public void onSuccess(Object data) {
                        LiveDataBus.get().with("userinfo", String.class).post("update");
                        ToastUtil.show("更新成功");
                        dismiss();
                    }
                });
            }
        });
    }

    @Override
    protected DialogAddOrUpdateUserInfoBinding getViewBinding() {
        return DialogAddOrUpdateUserInfoBinding.inflate(getLayoutInflater());
    }

    @Override
    protected void initData() {
        isEdit = getArguments().getBoolean("isEdit");
        userInfo = (UserInfo) getArguments().getSerializable("userInfo");

        if (userInfo != null) {
            setUserInfoDetail();
            setUserInfoEdit();
        } else {
            mBinding.btnSave.setTag("add");
            mBinding.btnSave.setText("保存");
            mBinding.titleName.setText("新增用户");
        }
        switchView(isEdit);


        RxView.clicks(mBinding.closeBtn)
                .throttleFirst(500, TimeUnit.MILLISECONDS)
                .subscribe(o -> {
                    dismiss();
                });

        RxView.clicks(mBinding.btnSave)
                .throttleFirst(500, TimeUnit.MILLISECONDS)
                .subscribe(o -> {
                    if (TextUtils.equals((CharSequence) mBinding.btnSave.getTag(), "add")) {
                        Object object = getParameters((String) mBinding.btnSave.getTag());
                        mViewModel.addUser(object);
                    } else if (TextUtils.equals((CharSequence) mBinding.btnSave.getTag(), "update")) {
                        Object object = getParameters((String) mBinding.btnSave.getTag());
                        mViewModel.updateUser(object);
                    } else if (TextUtils.equals((CharSequence) mBinding.btnSave.getTag(), "detail")) {
                        isEdit = true;
                        setUserInfoEdit();
                        switchView(isEdit);
                    }
                });


        RxView.clicks(mBinding.selectedPowerStation)
                .throttleFirst(500, TimeUnit.MILLISECONDS)
                .subscribe(o -> {
                    if (mPopupWindow == null) { //用户可能多次点击,不必重复创建对象
                        mPopupWindow = new AirDropdownPopupWindow(mContext, mBinding.selectedPowerStation, mBinding.selectedPowerStation, AirConfig.get().powerStations);
                        mPopupWindow.setDropdownCallBack(new AirDropdownPopupWindow.DropdownCallBack() {
                            @Override
                            public void select(SelectDict selectDict) {
                                powerStationId = selectDict.getValue();
                                mBinding.selectedPowerStation.setText(selectDict.getLabel());
                            }
                        });
                    }
                    mPopupWindow.showAsDropDown(mBinding.selectedPowerStation);//显示PopupWindow小弹窗
                });
        RxView.clicks(mBinding.selectedType)
                .throttleFirst(500, TimeUnit.MILLISECONDS)
                .subscribe(o -> {
                    if (mPopupWindowUserType == null) { //用户可能多次点击,不必重复创建对象
                        mPopupWindowUserType = new AirDropdownPopupWindow(mContext, mBinding.selectedType, mBinding.selectedType, getUserTypes());
                        mPopupWindowUserType.setDropdownCallBack(new AirDropdownPopupWindow.DropdownCallBack() {
                            @Override
                            public void select(SelectDict selectDict) {
                                userType = selectDict.getValue();
                                mBinding.selectedType.setText(selectDict.getLabel());
                            }
                        });
                    }
                    mPopupWindowUserType.showAsDropDown(mBinding.selectedType);//显示PopupWindow小弹窗
                });
    }

    @Override
    protected void requestNetwork() {

    }

    private Map getParameters(String tag) {
        Map<String, String> jsonObject = new HashMap<>();
        String account = mBinding.etAccount.getText().toString().trim();
        String name = mBinding.etName.getText().toString().trim();
        String remark = mBinding.etRemark.getText().toString().trim();
        if (TextUtils.isEmpty(account) || TextUtils.isEmpty(name) || TextUtils.isEmpty(powerStationId) || TextUtils.isEmpty(userType)) {
            ToastUtil.show("请完善用户信息！");
            return null;
        }
        jsonObject.put("account", account);
        jsonObject.put("name", name);
        jsonObject.put("remark", remark);
        jsonObject.put("powerStationId", powerStationId);
        jsonObject.put("type", userType);
        if (TextUtils.equals(tag, "update")) {
            jsonObject.put("id", userInfo.getId());
        }
        return jsonObject;
    }

    private void switchView(boolean isEdit) {
        mBinding.addUpdateUserInfo.setVisibility(isEdit ? View.VISIBLE : View.GONE);
        mBinding.userInfoDetail.setVisibility(isEdit ? View.GONE : View.VISIBLE);
    }

    private void setUserInfoDetail() {
        if (userInfo == null) return;
        if (isEdit) return;
        mBinding.account.setText(userInfo.getAccount());
        mBinding.name.setText(userInfo.getName());
        mBinding.typeDesc.setText(userInfo.getTypeDesc());
        mBinding.powerStationName.setText(userInfo.getPowerStationName());
        mBinding.createTime.setText(userInfo.getCreateTime());
        mBinding.updateTime.setText(userInfo.getUpdateTime());
        mBinding.remark.setText(userInfo.getRemark());

        powerStationId = userInfo.getPowerStationId();
        userType = String.valueOf(userInfo.getType());
        mBinding.btnSave.setTag("detail");
        mBinding.btnSave.setText("编辑");
        mBinding.titleName.setText("用户详情");

    }

    private void setUserInfoEdit() {
        if (userInfo == null) return;
        if (!isEdit) return;
        mBinding.etAccount.setText(userInfo.getAccount());
        mBinding.etName.setText(userInfo.getName());
        mBinding.selectedPowerStation.setText(userInfo.getPowerStationName());
        mBinding.selectedType.setText(userInfo.getTypeDesc());
        mBinding.etRemark.setText(userInfo.getRemark());
        mBinding.btnSave.setTag("update");
        mBinding.btnSave.setText("保存");
        mBinding.titleName.setText("编辑用户");

        powerStationId = userInfo.getPowerStationId();
        userType = String.valueOf(userInfo.getType());
    }


    private List<SelectDict> getUserTypes() {

        List<SelectDict> selectDicts = new ArrayList<>();
        SelectDict selectDict = new SelectDict("1", "工厂管理员");
        selectDicts.add(selectDict);
        selectDict = new SelectDict("2", "电站管理员");
        selectDicts.add(selectDict);
        selectDict = new SelectDict("9", "电站用户");
        selectDicts.add(selectDict);
        return selectDicts;
    }
}
